import time

import psutil
from flask import current_app
from flask_socketio import emit

from create_app import socketio, redis_pool


def task():
    pid = None
    while True:
        try:
            if not pid:
                pid = int(redis_pool.get('opcua_server_pid').decode('utf8'))
            process = psutil.Process(pid)
            status = {
                'pid': pid,
                'name': process.name(),
                'status': process.status(),
            }
            emit('message', status)
        except Exception as e:
            emit('message', str(e))
        time.sleep(1)


@socketio.on('connect', namespace='/real')
def test_connect():
    current_app.logger.info('client connected')
    task()


@socketio.on('disconnect', namespace='/real')
def test_disconnect():
    current_app.logger.info('client disconnected')


@socketio.on('message', namespace='/real')
def on_message(val):
    print(val)
